<?php

	session_start();
	if(!($_SESSION["username"])||($_SESSION["role"]!="TUT")){
		//not logged in or tutor
		header("location:index.php");
	}
	
	if (!isset($_GET['classid'])){
		header("location:manageclasses.php");
	}
	
	$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
	$objDB = mysql_select_db("Project 5.5");
	$strSQL = "SELECT * FROM classes WHERE Class_ID='".$_GET['classid']."'";
	$objQuery = mysql_query($strSQL);
	if($objQuery){
		// Get Document Path
		$strPath = realpath(basename(getenv($_SERVER["SCRIPT_NAME"])))."/temp";

		$objResult = mysql_fetch_array($objQuery);
		
		// Excel Document Root
		$filename = $objResult["Day"]." ".$objResult["Time"]." - ".$objResult["Location"]." (" . date('d-m-Y') . ").xls";

		// Connect to Excel.Application
		$xlApp = new COM("Excel.Application");
		$xlBook = $xlApp->Workbooks->Add();

		$xlBook->Worksheets(1)->Select;

		// Width & Height (A1:B1) 
		$xlApp->ActiveSheet->Range("A1:A1")->ColumnWidth = 28.0;
		$xlApp->ActiveSheet->Range("A1:A1")->HorizontalAlignment = -4108;
		$xlApp->ActiveSheet->Range("B1:B1")->ColumnWidth = 28.0;
		$xlApp->ActiveSheet->Range("B1:B1")->HorizontalAlignment = -4108;

		// Header
		$xlApp->ActiveSheet->Cells(1,1)->Value = "Student";
		$xlApp->ActiveSheet->Cells(1,1)->Font->Bold = True;
		$xlApp->ActiveSheet->Cells(1,2)->Value = "Group";
		$xlApp->ActiveSheet->Cells(1,2)->Font->Bold = True;
		
		$strSQL = 'SELECT u.User_ID, u.First_Name, u.Last_Name FROM users u, studentinfo s WHERE s.Class_ID="'.$_GET['classid'].'" AND u.User_ID=s.User_ID';
		$objQuery = mysql_query($strSQL);

		$intRows = 2;
		while($objResult = mysql_fetch_array($objQuery)){
		
			$sql = 'SELECT g.Group_Name FROM groups g, studentinfo s WHERE s.User_ID="'.$objResult["User_ID"].'" AND g.Group_ID=s.Group_ID';
			$result = mysql_fetch_row(mysql_query($sql));
			
			// Insert Row Details
			$xlApp->ActiveSheet->Cells($intRows,1)->Value = $objResult["First_Name"]." ".$objResult["Last_Name"];
			$xlApp->ActiveSheet->Cells($intRows,1)->HorizontalAlignment = -4131; 
			$xlApp->ActiveSheet->Cells($intRows,2)->Value = $result[0];
			$xlApp->ActiveSheet->Cells($intRows,2)->HorizontalAlignment = -4131; 
			
			$intRows++;
		}

		@unlink("./temp/".$filename);

		$xlBook->SaveAs($strPath."/".$filename);

		header("Content-Disposition: attachment; filename=\".$filename\"");
		header("Content-Type: application/vnd.ms-excel");
		readfile('temp/'.$filename);


		// Close & Quit
		$xlApp->Application->Quit();
		$xlApp = null;
		$xlBook = null;
		$xlSheet1 = null;

		@unlink("./temp/".$filename);

	}

	mysql_close($objConnect);
?>
